import Vue from 'vue'
import notification from 'ant-design-vue/es/notification'
import message from 'ant-design-vue/es/message'
import moment from 'moment'
import { axios } from '@/utils/request'
import { queryUnique } from '@/api/manage'

export const validateNum = [
  { type: 'number', message: '请输入数字', trigger: 'blur' },
  { pattern: /^([1-9]\d*)$/, message: '数字需大于0', trigger: 'blur' }
]

export function checkPhone(rule, value, callback) {
  const phoneReg = /^1[3|4|5|6|7|8][0-9]{9}$/
  if (!value) {
    return callback(new Error('手机号码不能为空'))
  }
  setTimeout(() => {
    if (!Number.isInteger(+value)) {
      callback(new Error('手机号码输入数字'))
    } else {
      if (phoneReg.test(value)) {
        callback()
      } else {
        callback(new Error('手机号码格式不正确'))
      }
    }
  }, 100)
}

export function serviceParam(str) {
  let urlArr = Vue.ls.get('urlArr')
  let obj = urlArr.filter(v => v.paraName === str)[0]
  return obj
}

export function timeFix() {
  const time = new Date()
  const hour = time.getHours()
  return hour < 9 ? '早上好' : hour <= 11 ? '上午好' : hour <= 13 ? '中午好' : hour < 20 ? '下午好' : '晚上好'
}

export function welcome() {
  const arr = ['休息一会儿吧', '准备吃什么呢?', '要不要打一把 DOTA', '我猜你可能累了']
  const index = Math.floor(Math.random() * arr.length)
  return arr[index]
}

/**
 * 触发 window.resize
 */
export function triggerWindowResizeEvent() {
  const event = document.createEvent('HTMLEvents')
  event.initEvent('resize', true, true)
  event.eventType = 'message'
  window.dispatchEvent(event)
}

export function handleScrollHeader(callback) {
  let timer = 0

  let beforeScrollTop = window.pageYOffset
  callback = callback || function () { }
  window.addEventListener(
    'scroll',
    event => {
      clearTimeout(timer)
      timer = setTimeout(() => {
        let direction = 'up'
        const afterScrollTop = window.pageYOffset
        const delta = afterScrollTop - beforeScrollTop
        if (delta === 0) {
          return false
        }
        direction = delta > 0 ? 'down' : 'up'
        callback(direction)
        beforeScrollTop = afterScrollTop
      }, 50)
    },
    false
  )
}

export function isIE() {
  const bw = window.navigator.userAgent
  const compare = (s) => bw.indexOf(s) >= 0
  const ie11 = (() => 'ActiveXObject' in window)()
  return compare('MSIE') || ie11
}

// 医德医风 输入的分数未匹配到数组时，判断更接近最大最小值来显示数组
export function noMatchLevel(levelArr, grade) {
  let arr2 = []
  let minScore = levelArr[0].minScore
  let maxScore = levelArr[0].maxScore
  levelArr.map(v => {
    if (v.maxScore >= maxScore) {
      maxScore = v.maxScore
    }
    if (v.minScore <= minScore) {
      minScore = v.minScore
    }
  })

  if (Math.abs(grade - maxScore) > Math.abs(grade - minScore)) {
    // 更靠近最大值
    arr2 = levelArr.filter(v => v.minScore === minScore)
  } else {
    arr2 = levelArr.filter(v => v.maxScore === maxScore)

  }

  return arr2
}

/**
 * Remove loading animate
 * @param id parent element id or class
 * @param timeout
 */
export function removeLoadingAnimate(id = '', timeout = 1500) {
  if (id === '') {
    return
  }
  setTimeout(() => {
    document.body.removeChild(document.getElementById(id))
  }, timeout)
}

/**
 *
 * @param {提醒类型} type
 * @param {提醒标题} mes
 * @param {提醒描述} des
 */
export function openNotification(type, mes, des = '') {
  notification.config({
    placement: 'bottomRight'
  })

  notification[type]({
    message: mes,
    description: des,
    duration: 5
  });
}

/**
 * @param {键} key
 * @param {值} value
 */
export function setSession(key, value) {
  sessionStorage.setItem(key, JSON.stringify(value))
}

export function getSession(key) {
  return JSON.parse(sessionStorage.getItem(key))
}

export function removeSession(key) {
  sessionStorage.removeItem(key)
}

/**
 * 格式化时间
 */
export function formatTime(time, type = 'min') {
  const date = new Date(time)
  const year = date.getFullYear()
  const mon = buLing(date.getMonth() + 1)
  const day = buLing(date.getDate())
  const h = buLing(date.getHours())
  const m = buLing(date.getMinutes())
  const s = buLing(date.getSeconds())
  if (type === 'min') {
    return year + '-' + mon + '-' + day + ' ' + h + ':' + m
  } else if (type === 'day') {
    return year + '-' + mon + '-' + day
  } else if (type === 'seconds') {
    return year + '-' + mon + '-' + day + ' ' + h + ':' + m + ':' + s

  }
}

export function getMonitorTime() {
  let time = Vue.ls.get('monitorTime')
  let param = null
  if (time.split('-').length > 1) {
    param = { month: time }
  } else {
    param = { year: time }
  }
  return param
}

function buLing(num) {
  return num < 10 ? '0' + num : num
}

/**
 * @param {时间，moment长串格式} 
 * 格式化年月日
 */
export function formatY(date) {
  return moment(date).format('YYYY-MM-DD')
}

/**
 * 获取字典数据
 */
export function getDicData(parentKey, key) {
  const arr = Vue.ls.get('dictionaryData')
  const pIndex = arr.findIndex(v => v.key === parentKey)
  const childArr = arr[pIndex].children
  const index = childArr.findIndex(v => v.key === key)
  return childArr[index].children
}

/**
 * 图片上传之前处理
 */
export function beforeUpload(file) {
  const isLt2M = file.size / 1024 / 1024 < 10
  if (!isLt2M) {
    message.error('图片文件太大!')
  }
  return isLt2M
}

/**
 * 图片转化png64
 */
export function getBase64(img, callback) {
  const reader = new FileReader()
  reader.addEventListener('load', () => callback(reader.result))
  reader.readAsDataURL(img)
}

// 布尔值转为数字
export function boolTransNum(obj) {
  const newObj = Object.assign({}, obj)
  Object.keys(newObj).forEach(v => {
    if (newObj[v] === true) {
      newObj[v] = 1
    }
    if (newObj[v] === false) {
      newObj[v] = 0
    }
  })
  return newObj
}

// 获取前一个月
export function getPreMonth(date) {
  var arr = date.split('-')
  var year = arr[0] //获取当前日期的年份
  var month = arr[1] //获取当前日期的月份
  var day = arr[2] //获取当前日期的日
  var days = new Date(year, month, 0)
  days = days.getDate() //获取当前日期中月的天数
  var year2 = year
  var month2 = parseInt(month) - 1
  if (month2 == 0) {
    year2 = parseInt(year2) - 1
    month2 = 12
  }
  var day2 = day
  var days2 = new Date(year2, month2, 0)
  days2 = days2.getDate()
  if (day2 > days2) {
    day2 = days2
  }
  if (month2 < 10) {
    month2 = '0' + month2
  }
  var t2 = year2 + '-' + month2 + '-' + day2
  return t2
}

/**
 * 统一修改排序方法
 */
export async function orderChange(row, order, id, urlParam, uri = '/system/') {
  console.log('row', row, order, id, urlParam);

  if (row[order] > 100 || row[order] < 0) {
    message.error('排序值限制0-100')
    return false
  }
  if (Object.is(row[order], NaN)) {
    message.error('您输入不是一个数字')
    return false
  }
  let url = uri + urlParam + '/updateOrder'
  const params = { id: row[id], [order]: row[order] }
  const res = await axios({
    url,
    method: 'put',
    params
  })
  return res
}

// 手机号验证
export function isvalidPhone(str) {
  const reg = /^1[3|4|5|7|8][0-9]\d{8}$/
  return reg.test(str)
}

/**
 * 处理序号方法
 */

export function indexMethod(index) {
  // (pageObj.currentPage - 1)*pageObj.size + scope.$index + 1
  return index + 1
}

/**
 * 供应商处理状态方法
 */
export function judgeState(state) {
  let str = ''
  switch (state) {
    case 0:
      str = '已准入'
      break
    case 1:
      str = '未审核'
      break
    case 2:
      str = '审核中'
      break
    case 3:
      str = '过期'
      break
    default:
      str = '停用'
      break
  }
  return str
}

/**
 * 供应商处理颜色方法
 */
export function judgeColor(state) {
  let str = ''
  switch (state) {
    case 0:
      str = 'success'
      break
    case 1:
      str = ''
      break
    case 2:
      str = 'warning'
      break
    case 3:
      str = 'danger'
      break
    default:
      break
  }
  return str
}

/**
 * 综合考评-判断周期
 * @param {*} num 
 */
export function judgeRange(num) {
  let str = ''
  switch (num) {
    case 0:
      str = '临时'
      break
    case 2:
      str = '周'
      break
    case 3:
      str = '月'
      break
    case 4:
      str = '季度'
      break
    case 5:
      str = '年'
      break
    default:
      break
  }
  return str
}

/**
 * 综合考评-判断状态文字
 * @param {*} num 
 */
export function judgeEvalState(num) {
  let str = ''
  switch (num) {
    case 1:
      str = '暂停'
      break
    case 2:
      str = '启用'
      break
    case 3:
      str = '到期'
      break
    case 4:
      str = '作废'
      break
    default:
      break
  }
  return str
}

/**
 * 综合考评-判断状态颜色
 * @param {*} num 
 */
export function judgeType(num) {
  let str = ''
  switch (num) {
    case 1:
      str = 'warning'
      break
    case 2:
      str = 'success'
      break
    case 3:
      str = 'warning'
      break
    case 4:
      str = 'danger'
      break
    default:
      break
  }
  return str
}

/**
 * 固定资产-资产状态文字
 * @param {*} num 
 */
export function stateWord(num) {
  let str = ''
  switch (num) {
    case '0':
      str = '正常'
      break
    case '1':
      str = '遗失'
      break
    case '2':
      str = '标签破损'
      break
    case '3':
      str = '维修'
      break
    case '4':
      str = '报废'
      break
    case '5':
      str = '违规异动'
      break
    default:
      break
  }
  return str
}

/**
 * 固定资产-资产状态颜色
 * @param {*} num 
 */
export function stateType(num) {
  let str = ''
  switch (num) {
    case '0':
      str = 'success'
      break
    case '1':
      str = 'danger'
      break
    case '2':
      str = 'orange'
      break
    case '3':
      str = ''
      break
    case '4':
      str = 'danger'
      break
    case '5':
      str = 'info'
      break
    default:
      break
  }
  return str
}

/**
 * 用户管理-检测用户名/手机号唯一性
 */
export async function checkName(obj) {
  // console.log(key, value)
  const res = await queryUnique(obj)
  if (res !== undefined) {
    return true
  } else {
    return false
  }
}

